import React, { useEffect, useRef, useState } from 'react';
import ReactDom from 'react-dom';
import { useDispatch, useMappedState, StoreContext } from 'redux-react-hook';
import { QUE_LIST } from './constant';
import styles  from './index.style';
import configStyles  from './config.style';
import { getRandomWords } from './utils';


function App() {
  const [ store, setStore ] = useState({
    type: 'question', // question | config // 答题或配置
    configValue: {
      checkList: new Array(30).fill(true),
      time: 60,
      count: 10,
    },

    step: 0, // 0, 一开始 | 1, 一分钟 | 2，结束了
    list: [
      // {
      //   line: '一曲新词酒一杯,去年天气:亭台',
      //   word: '旧',
      //   // c: undefined,  | true | false
      // }
    ],
    listIndex: 0, // 答题次序
    otherWords: [], // 待选的词
    // count: 60,
    count: 60,
    wordCount: 10, // 出多少选项
  }); 
  const storeRef = useRef(null);
  storeRef.current = store;

  useEffect(() => {
    let location = window.location;
    let qIds = new URL(location).searchParams.get('q') || '1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20';
    let time = Number(new URL(location).searchParams.get('t')) || 60;
    let wordCount = Number(new URL(location).searchParams.get('w')) || 10;

    actionInit(qIds, time, wordCount);
  }, []);

  const actionInit = (qIds, time, wordCount) => {
    let type = new URL(location).searchParams.get('type');
    if ( type === 'config' ) { 
      return setStore({ ...store,
        type: 'config',
      });
    }


    let list = qIds.split('-').map((i) => {
      return QUE_LIST[ Number(i) - 1 ];
    });
    setStore({ ...store,
      list,
      count: time,
      wordCount,
    });
  };

  const onStart = () => {
    setStore({
      ...store,
      step: 1,
      otherWords: getRandomWords( 
        store.list[ store.listIndex ].word,
        store.wordCount 
      )
    });

    setTimeout(() => {
      onCountMinus();
    }, 1000);
  }

  const onClickWord = (word) => {
    let cur = store.list[ store.listIndex ];
    if ( cur.word === word ) {
      // 正确
      let list = store.list.map((l, index) => {
        if ( index === store.listIndex ) {
          return { ...l, 
            c: true,
          };
        } else {
          return l;
        }
      });
      setStore({ ...store, 
        list,
        listIndex: store.listIndex + 1,
        otherWords: getRandomWords( 
          store.list[ store.listIndex + 1 ]?.word,
          store.wordCount
        )
      });
      let cAudio = document.getElementById('vc');
      let wAudio = document.getElementById('vw');
      cAudio.pause();
      wAudio.pause();
      cAudio.currentTime = 0;
      wAudio.currentTime = 0;
      cAudio.play();
      document.body.style.background = 'rgb(202 255 230)';
      setTimeout(() => {
        document.body.style.background = '#ffffff';
      }, 500);
    } else {
      // 错误
      let list = store.list.map((l, index) => {
        if ( index === store.listIndex ) {
          return { ...l, 
            c: false,
          };
        } else {
          return l;
        }
      });
      setStore({ ...store, 
        list,
        listIndex: store.listIndex + 1,
        otherWords: getRandomWords( 
          store.list[ store.listIndex + 1 ]?.word,
          store.wordCount
        )
      });
      let cAudio = document.getElementById('vc');
      let wAudio = document.getElementById('vw');
      cAudio.pause();
      wAudio.pause();
      cAudio.currentTime = 0;
      wAudio.currentTime = 0;
      wAudio.play();
      document.body.style.background = 'rgb(255 222 222)';
      setTimeout(() => {
        document.body.style.background = '#ffffff';
      }, 500);
    }
  }

  const onCountMinus = () => {
    let store = storeRef.current;

    if ( store.count === 0 ) {
      // 计算正确错误率 
      return setStore({
        ...store,
        step: 2, // 游戏结束
        otherWords: [],
        listIndex: 0,
        count: 60,
      });
    }

    setStore({
      ...store,
      count: store.count - 1,
    });

    setTimeout(() => {
      onCountMinus();
    }, 1000);
  }

  const utilsGetFinalHref = () => {
    if ( store.type !== 'config' ) {
      return '';
    }
    let qArr = [];
    ( store.configValue.checkList ).map((v, index) => {
      if (v === true ) {
        qArr.push(index + 1);
      }
    });
    return `https://ahkari.gitee.io/a-word-game/?q=${qArr.join('-')}&t=${
      store.configValue.time || 60
    }&w=${
      store.configValue.count || 10
    }`
  }

  // console.log( 'state-->', state );

  // render
  const curQ = store.list[ store.listIndex ];
  let curS = 0;
  store.list.map((l) => {
    if ( l.c === true ) {
      curS += 1;
    }
  });

  console.log( 'store--->', store );


  if ( store.type === 'config' ) {
    return <div style={configStyles.homeContainer}>
      <div style={{
        margin: '10px 0px'
      }}>题目选择：</div>
      <div>
        {
          QUE_LIST.map((v, index) => {
            return <span style={{
              marginRight: 10, 
              marginBottom: 4,
              border: '1px solid #999',
              padding: 4,
              display: 'inline-block',
            }}>
              <input 
                type="checkbox" 
                id={`q${index}`} 
                name={`q${index}`} 
                checked={store.configValue.checkList[ index ]}
                onChange={(e) => {
                  // console.log( 'onChange-->', e );
                  let checkList = store.configValue.checkList;
                  checkList[ index ] = e.target.checked;
                  setStore({ ...store, 
                    configValue: { ...store.configValue, 
                      checkList,
                    },
                  });
                }}  
              />
              <label htmlFor={`q${index}`}>「{index + 1}」{
                `题干：${v.line}；答案：${v.word}`
              }</label>
            </span>;
          })
        }
      </div>
      <div style={{
        margin: '10px 0px'
      }}>比赛时间：</div>
      <div>
        <input type="number" id="glo-v-time" value={store.configValue.time} onChange={(e) => {
          setStore({ ...store, 
            configValue: { ...store.configValue, 
              time: e.target.value
            },
          });
        }} /> 秒
      </div>
      <div style={{
        margin: '10px 0px'
      }}>候选词数量（不可为0）：</div>
      <div>
        <input type="number" id="glo-v-count" value={store.configValue.count} onChange={(e) => {
          setStore({ ...store, 
            configValue: { ...store.configValue, 
              count: e.target.value
            },
          });
        }} /> 个
      </div>

      <div style={{
        margin: '50px, 0px',
        fontSize: 20,
      }}>答题链接如下：</div>
      <div>
        <a href={utilsGetFinalHref()} target="_blank">{
          utilsGetFinalHref()
        }</a>
      </div>
    </div>
  }


  return (
    <div style={styles.homeContainer}>
      {
        store.step === 0
         && <div style={styles.btn} onClick={onStart}>
          {/* 点字成诗 */}
          <img src="https://gw.alicdn.com/imgextra/i1/O1CN017jROm21fkewVrexst_!!6000000004045-2-tps-320-90.png" alt="" style={{
            width: 320,
            height: 90,
          }} />
         </div>
      }
      {
        store.step === 2 && <>
          <div style={{
            ...styles.score,
          }}>
            <span style={{ ...styles.scoreFinal
            }}>
              { Math.floor( (curS / store.list.length) * 100 ) }
            </span>
            <img style={{
              ...styles.scoreLine
            }} src="https://gw.alicdn.com/imgextra/i3/O1CN01tiad9t1MkDrzzSw6N_!!6000000001472-2-tps-1099-405.png" alt="" />
          </div>
          <div style={{
            ...styles.over,
            height: 100,
          }}>
            您已答完！您总共答对 <span style={{
              color: 'rgb(17 208 142)',
              marginLeft: 20,
              marginRight: 20,
            }}>{curS}</span> 道题！
          </div>
          <div style={styles.rAll}>
            {
              store.list.slice(0, Math.ceil(store.list.length / 2) ).map((l, index) => {
                return <div style={styles.rEach} key={index}>
                  {
                    l.c === true 
                      ? <img style={{
                        width: 50,
                        height: 50,
                      }} src="https://gw.alicdn.com/imgextra/i3/O1CN01v5Y7V91nh0i8wY7Cl_!!6000000005120-2-tps-128-128.png" />
                      : (
                        l.c === false 
                          ? <img style={{
                            width: 50,
                            height: 50,
                          }} src="https://gw.alicdn.com/imgextra/i4/O1CN011cWUWv1JoOcu0cwrh_!!6000000001075-2-tps-128-128.png" />
                          : <div></div>
                      )
                  }
                </div>;
              })
            }
          </div>
          <div style={styles.rAll}>
            {
              store.list.slice(Math.ceil(store.list.length / 2), store.list.length).map((l, index) => {
                return <div style={styles.rEach} key={index}>
                  {
                    l.c === true 
                      ? <img style={{
                        width: 50,
                        height: 50,
                      }} src="https://gw.alicdn.com/imgextra/i3/O1CN01v5Y7V91nh0i8wY7Cl_!!6000000005120-2-tps-128-128.png" />
                      : (
                        l.c === false 
                          ? <img style={{
                            width: 50,
                            height: 50,
                          }} src="https://gw.alicdn.com/imgextra/i4/O1CN011cWUWv1JoOcu0cwrh_!!6000000001075-2-tps-128-128.png" />
                          : <div></div>
                      )
                  }
                </div>;
              })
            }
          </div>
        </>
      }
      {
        store.step === 1 && <>
          <div style={styles.count}>
            <img src={'https://gw.alicdn.com/imgextra/i2/O1CN01dZzW0421KwFCPVy8U_!!6000000006967-2-tps-128-128.png'} 
              style={styles.img} 
              alt="" 
            />
            <div style={styles.span}>{store.count} 秒</div>
            <div style={styles.qcur}>（第 { (
              store.listIndex + 1 ) > store.list.length
                ? store.list.length
                : store.listIndex + 1
            } / {store.list.length} 题）</div>
          </div>
          
          {
            store.listIndex === store.list.length && <div style={styles.over}>
              您已答完！请等待时间结束
            </div>
          }

          {
            store.listIndex !== store.list.length && <div style={styles.qall}>
              {
                curQ.line.split(',').map((q, index) => {
                  let wArr = q.split(':');
                  if ( wArr.length === 2 ) {
                    return <div key={index} style={styles.qEach}>
                    {wArr[0]}<div style={styles.qInner} >?</div>{wArr[1]}
                  </div>;
                  } else {
                    return <div key={index} style={styles.qEach}>
                    {q}
                  </div>;
                  }
                })
              }
            </div>
          }

          {
            store.listIndex !== store.list.length && <div style={styles.otherWrap}>
              <div style={styles.otherL}>
                {
                  store.otherWords.slice(0, Math.ceil(store.wordCount / 2) ).map((w, index) => {
                    return <div style={styles.otherW} key={index} onClick={() => {
                      onClickWord(w);
                    }}>
                      {w}
                    </div>;
                  })
                }
              </div>
              <div style={styles.otherL}>
                {
                  store.otherWords.slice( Math.ceil(store.wordCount / 2) ).map((w, index) => {
                    return <div style={styles.otherW} key={index} onClick={() => {
                      onClickWord(w);
                    }}>
                      {w}
                    </div>;
                  })
                }
              </div>
            </div>
          }
          

        </>
      }
        
    </div>
  );
}





let nodeDom = window.document.createElement('div');
// Amy 和 Ahari 故事挂载的节点
nodeDom.id = 'amy-ahkari';
// window.document.body.classList.add(HOME_STYLE_NAME);

window.document.body.append(nodeDom);
function AppEntry() {
  return (
      <App />
  )
}
ReactDom.render(
  <AppEntry />,
  document.getElementById('amy-ahkari'),
);
